package com.baizhi.service.impl;

import com.baizhi.dao.PersonDao;
import com.baizhi.entity.Person;
import com.baizhi.service.PersonService;
import com.baizhi.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class PersonServiceImpl implements PersonService {
    @Override
    public int addPerson(Person p) {
        int result = 0;
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            PersonDao dao = sqlSession.getMapper(PersonDao.class);
            result = dao.insertPerson(p);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
        } finally {
            MyBatisUtils.close(sqlSession);
        }
        return result;
    }

    @Override
    public int deletePerson(Integer id) {
        int result = 0;
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            PersonDao dao = sqlSession.getMapper(PersonDao.class);
            result = dao.deletePerson(id);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
        } finally {
            MyBatisUtils.close(sqlSession);
        }
        return result;
    }

    @Override
    public List<Person> selectPerson(String name, Integer pageNum, Integer pageSize) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        PersonDao dao = sqlSession.getMapper(PersonDao.class);
        Integer start = (pageNum-1)*pageSize;
        List<Person> list = dao.selectPerson(name,start, pageSize);
        MyBatisUtils.close(sqlSession);
        return list;
    }

    @Override
    public int count(String name) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        PersonDao dao = sqlSession.getMapper(PersonDao.class);
        int count = dao.count(name);
        MyBatisUtils.close(sqlSession);
        return count;
    }
}
